<template>
  <t-dialog :visible.sync="visible" header="编 辑" confirm-btn="确定" cancel-btn="取消" :width="dialogWidth"
    @confirm="handleConfirm" @cancel="handleCancel" @close="handleCancel">
    <fc-designer ref="designer" height="100vh" :config="config" />
  </t-dialog>
</template>
<script setup lang="ts">
import { ref, defineExpose, computed } from 'vue';
import { MessagePlugin } from 'tdesign-vue-next';
import { update, getById } from '@/api/userCenter/form';
// 可以在此处获取设计器实例或进行其他操作
const designer = ref?.(null);
const config = {
  // showSaveBtn: true,
}
const visible = ref?.(false);
const loading = ref?.(false);
const formRef = ref?.(null);
const form = ref?.({
  id: '',
  title: '',
  content: '',
  option: '',
});
// 计算对话框宽度为视窗宽度的95%
const dialogWidth = computed?.(() => {
  return `${window.innerWidth * 0.95}px`;
});
const handleConfirm = async () => {
  form.value.content = JSON?.stringify(designer.value.getRule())
  form.value.option = JSON?.stringify(designer.value.getOptions())
  if (!formRef) return;

  loading.value = true;
  try {
    await update(form.value);
    MessagePlugin?.success?.(`操作成功`);
    visible.value = false;
    emit?.('success');
    formRef?.value?.reset();
  } catch (t) {
    console.log(t);
    loading.value = false;
  } finally {
    loading.value = false;
  }
};
const handleCancel = () => {
  visible.value = false;
};
const openDialog = async (id?: string) => {
  designer.value.setOptions(null)
  designer.value.setRule(null)
  visible.value = true;
  if (id) {
    loading.value = true;
    form.value.id = id;
    const val = await getById(id);
    if (val && Object?.keys?.(val)?.length) {
      form.value = { ...form?.value, ...val, }
      designer.value.setOptions(JSON.parse(val.option))
      designer.value.setRule(JSON.parse(val.content))
    }
    loading.value = false;
  }
};
defineExpose({
  openDialog,
});
const emit = defineEmits(['success']);
</script>
<style lang="less" scoped>
/* 可以在这里添加自定义样式 */
</style>
